<template>
  <div class="profile-edit">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="个人信息管理"
      left-arrow
      @click-left="$router.back()"
      fixed
    />

    <div class="content">
      <van-form @submit="handleSubmit">
        <!-- 头像 -->
        <div class="avatar-upload">
          <van-uploader
            v-model="fileList"
            :max-count="1"
            :after-read="afterRead"
            accept="image/*"
          >
            <div class="avatar-wrapper">
              <van-image
                v-if="userForm.avatar || userInfo.avatar"
                width="80"
                height="80"
                round
                :src="userForm.avatar || userInfo.avatar"
                fit="cover"
              />
              <van-icon
                v-else
                name="contact"
                size="80"
                class="avatar-placeholder"
              />
              <div class="upload-text">点击更换头像</div>
            </div>
          </van-uploader>
        </div>

        <!-- 基本信息 -->
        <van-cell-group inset title="基本信息">
          <van-field
            v-model="userForm.nickname"
            name="nickname"
            label="昵称"
            placeholder="请输入昵称"
            :rules="[{ required: true, message: '请输入昵称' }]"
          />

          <van-field
            v-model="userForm.username"
            name="username"
            label="用户名"
            readonly
            :rules="[{ required: true, message: '请输入用户名' }]"
          />

          <van-field name="gender" label="性别">
            <template #input>
              <van-radio-group v-model="userForm.gender" direction="horizontal">
                <van-radio :name="0">男</van-radio>
                <van-radio :name="1">女</van-radio>
                <van-radio :name="2">保密</van-radio>
              </van-radio-group>
            </template>
          </van-field>

          <van-field
            v-model="userForm.email"
            name="email"
            label="邮箱"
            placeholder="请输入邮箱"
            :rules="[
              {
                pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
                message: '请输入正确的邮箱格式',
              },
            ]"
          />

          <van-field
            v-model="userForm.phone"
            name="phone"
            label="手机号"
            placeholder="请输入手机号"
            :rules="[
              {
                pattern: /^1[3-9]\d{9}$/,
                message: '请输入正确的手机号',
              },
            ]"
          />
        </van-cell-group>

        <!-- 个人简介 -->
        <van-cell-group inset title="个人简介" class="bio-group">
          <van-field
            v-model="userForm.bio"
            name="bio"
            label="简介"
            type="textarea"
            placeholder="请输入个人简介"
            rows="3"
            maxlength="200"
            show-word-limit
          />
        </van-cell-group>

        <!-- 隐私设置 -->
        <van-cell-group inset title="隐私设置" class="privacy-group">
          <van-cell title="公开我的收藏">
            <template #right-icon>
              <van-switch v-model="userForm.showFavorites" size="20" />
            </template>
          </van-cell>

          <van-cell title="公开我的评分">
            <template #right-icon>
              <van-switch v-model="userForm.showRatings" size="20" />
            </template>
          </van-cell>
        </van-cell-group>

        <!-- 提交按钮 -->
        <div style="margin: 16px">
          <van-button
            round
            block
            type="primary"
            native-type="submit"
            :loading="loading"
          >
            保存
          </van-button>
        </div>
      </van-form>
    </div>

    <!-- 修改密码弹窗 -->
    <van-action-bar>
      <van-action-bar-button
        type="warning"
        text="修改密码"
        @click="showPasswordDialog = true"
      />
    </van-action-bar>

    <van-dialog
      v-model:show="showPasswordDialog"
      title="修改密码"
      show-cancel-button
      @confirm="handleChangePassword"
    >
      <van-form>
        <van-cell-group inset>
          <van-field
            v-model="passwordForm.oldPassword"
            name="oldPassword"
            label="原密码"
            type="password"
            placeholder="请输入原密码"
            :rules="[{ required: true, message: '请输入原密码' }]"
          />

          <van-field
            v-model="passwordForm.newPassword"
            name="newPassword"
            label="新密码"
            type="password"
            placeholder="请输入新密码"
            :rules="[
              { required: true, message: '请输入新密码' },
              { min: 6, max: 20, message: '密码长度为6-20个字符' },
            ]"
          />

          <van-field
            v-model="passwordForm.confirmPassword"
            name="confirmPassword"
            label="确认密码"
            type="password"
            placeholder="请再次输入新密码"
            :rules="[
              { required: true, message: '请再次输入新密码' },
              {
                validator: (val) => val === passwordForm.newPassword,
                message: '两次输入的密码不一致',
              },
            ]"
          />
        </van-cell-group>
      </van-form>
    </van-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { showToast, showSuccessToast } from "vant";
import { useUserStore } from "../../stores/userStore";
import { getUserInfo as getAuthUserInfo, setUserInfo } from "../../utils/auth";

// 模拟API函数
const getUserInfo = async (userId) => {
  // 这里替换为实际的API调用
  console.log(`获取用户${userId}的详细信息`);

  // 模拟数据 - 实际应从本地存储或API获取
  const localUserInfo = getAuthUserInfo();

  return {
    code: 200,
    data: {
      id: localUserInfo?.id || 1,
      username: localUserInfo?.username || "user123",
      nickname: localUserInfo?.nickname || "用户昵称",
      email: localUserInfo?.email || "user@example.com",
      phone: localUserInfo?.phone || "",
      gender: localUserInfo?.gender !== undefined ? localUserInfo.gender : 0,
      avatar: localUserInfo?.avatar || "https://img.yzcdn.cn/vant/cat.jpeg",
      bio: localUserInfo?.bio || "",
      showFavorites:
        localUserInfo?.showFavorites !== undefined
          ? localUserInfo.showFavorites
          : true,
      showRatings:
        localUserInfo?.showRatings !== undefined
          ? localUserInfo.showRatings
          : true,
    },
  };
};

const updateUserInfo = async (userId, data) => {
  // 这里替换为实际的API调用
  console.log(`更新用户${userId}的信息`, data);

  // 模拟成功响应
  return {
    code: 200,
    message: "更新成功",
    data: {
      ...data,
      id: userId,
    },
  };
};

const changePassword = async (userId, data) => {
  // 这里替换为实际的API调用
  console.log(`修改用户${userId}的密码`, data);

  // 模拟成功响应
  return { code: 200, message: "密码修改成功" };
};

const router = useRouter();
const userStore = useUserStore();

// 状态变量
const loading = ref(false);
const fileList = ref([]);
const userInfo = ref({});
const showPasswordDialog = ref(false);

// 表单数据
const userForm = reactive({
  nickname: "",
  username: "",
  email: "",
  phone: "",
  gender: 0,
  avatar: "",
  bio: "",
  showFavorites: true,
  showRatings: true,
});

// 密码表单
const passwordForm = reactive({
  oldPassword: "",
  newPassword: "",
  confirmPassword: "",
});

// 获取用户ID
const userId = userStore.userId;

// 上传头像后的处理
const afterRead = (file) => {
  // 在真实环境中，这里应该调用上传API
  console.log("上传头像", file);

  // 模拟上传成功，直接使用本地文件URL
  userForm.avatar = file.content;
};

// 加载用户信息
const loadUserInfo = async () => {
  try {
    loading.value = true;
    const res = await getUserInfo(userId);

    if (res.code === 200 && res.data) {
      userInfo.value = res.data;

      // 设置表单初始值
      Object.keys(userForm).forEach((key) => {
        if (res.data[key] !== undefined) {
          userForm[key] = res.data[key];
        }
      });

      // 如果有头像，设置到文件列表
      if (res.data.avatar) {
        userForm.avatar = res.data.avatar;
      }
    } else {
      showToast("获取用户信息失败");
    }
  } catch (error) {
    console.error("加载用户信息失败", error);
    showToast("获取用户信息失败");
  } finally {
    loading.value = false;
  }
};

// 提交表单
const handleSubmit = async () => {
  try {
    loading.value = true;
    const res = await updateUserInfo(userId, userForm);

    if (res.code === 200) {
      showSuccessToast("保存成功");

      // 更新本地存储的用户信息
      const updatedUserInfo = {
        ...getAuthUserInfo(),
        ...res.data,
      };
      setUserInfo(updatedUserInfo);

      // 更新用户store
      userStore.userInfo = updatedUserInfo;

      // 返回上一页
      router.back();
    } else {
      showToast("保存失败");
    }
  } catch (error) {
    console.error("更新用户信息失败", error);
    showToast("保存失败");
  } finally {
    loading.value = false;
  }
};

// 修改密码
const handleChangePassword = async () => {
  try {
    if (passwordForm.newPassword !== passwordForm.confirmPassword) {
      showToast("两次输入的密码不一致");
      return;
    }

    const res = await changePassword(userId, {
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword,
    });

    if (res.code === 200) {
      showSuccessToast("密码修改成功");

      // 清空表单
      passwordForm.oldPassword = "";
      passwordForm.newPassword = "";
      passwordForm.confirmPassword = "";
    } else {
      showToast("密码修改失败");
    }
  } catch (error) {
    console.error("修改密码失败", error);
    showToast("密码修改失败");
  }
};

onMounted(() => {
  loadUserInfo();
});
</script>

<style scoped>
.profile-edit {
  padding-top: 46px;
  padding-bottom: 50px;
  min-height: 100vh;
  background-color: #f7f8fa;
}

.content {
  padding: 16px;
}

.avatar-upload {
  display: flex;
  justify-content: center;
  margin: 20px 0;
}

.avatar-wrapper {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.avatar-placeholder {
  color: #ddd;
  background-color: #f2f3f5;
  border-radius: 50%;
  padding: 10px;
}

.upload-text {
  margin-top: 8px;
  font-size: 12px;
  color: #969799;
}

.bio-group,
.privacy-group {
  margin-top: 12px;
}
</style>
